﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace RusIS.CMS
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());

            // Мой пользовательский фильтр безопасности
            filters.Add(new RusIS.CMS.Security.MySecurityFilter());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            BundleTable.Bundles.RegisterTemplateBundles();
        }


        protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated && !String.IsNullOrEmpty(HttpContext.Current.User.Identity.Name))
                HttpContext.Current.User = BusinessLogic.Security.AuthenticationService.AuthorizeUser(HttpContext.Current.User.Identity.Name);
        }


        protected void Application_Error(object sender, EventArgs e)
        {
            try
            {
                HttpContext ctx = HttpContext.Current;
                Exception ex = ctx.Server.GetLastError();

                ctx.Response.Clear();

                RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext;
                IController controller = new RusIS.CMS.Controllers.ErrorController(); // Тут можно использовать любой контроллер, например тот что используется в качестве базового типа
                var context = new ControllerContext(rc, (ControllerBase)controller);

                var viewResult = new ViewResult();

                var httpException = ex as HttpException;
                if (httpException != null)
                {
                    switch (httpException.GetHttpCode())
                    {
                        case 403:
                            viewResult.ViewName = "AccessDenied";
                            break;

                        //case 404:
                        //    viewResult.ViewName = "Error404";
                        //    break;

                        //case 500:
                        //    viewResult.ViewName = "Error500";
                        //    break;

                        default:
                            viewResult.ViewName = "Error";
                            break;
                    }
                }
                else
                {
                    viewResult.ViewName = "Error";
                }

                viewResult.ViewData.Model = new HandleErrorInfo(ex, context.RouteData.GetRequiredString("controller"), context.RouteData.GetRequiredString("action"));
                viewResult.ExecuteResult(context);
                ctx.Server.ClearError();
            }
            catch (Exception ex)
            {
            }
        }



    }
}